package com.zwface.demo.utils;

import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;

import java.lang.ref.WeakReference;

/**
 * created by 张中文
 * on 2020/2/2
 * 描述：软键盘管理工具
 */
public class SoftKeyBoardUtils {
    /**
     * 显示或隐藏软键盘， 若软键盘处于显示状态，则执行隐藏； 若软键盘处于隐藏状态,则执行显示
     *
     * @param activity
     */
    public static void showOrHideSoftInput(Activity activity) {
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    /**
     * 关闭输入法
     */
    public static void hideSoftInput(Activity activity) {
        if (activity == null) {
            return;
        }

        if (activity.getCurrentFocus() == null) {
            activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
            return;
        }

        InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(),
                InputMethodManager.HIDE_NOT_ALWAYS);
    }

    /**
     * 关闭输入法
     */
    public static void hideSoftInput(Context context, View view) {

        WeakReference contextWeakReference = new WeakReference(context);

        InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);

        inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }


    /**
     * 判断键盘是否打开
     *
     * @param inputMethodManager
     * @return
     */
    public static Boolean isOpenKeyBoard(InputMethodManager inputMethodManager, View view) {
        if (inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0)) {
            inputMethodManager.showSoftInput(view, 0);
            return true;
            //软键盘已弹出
        } else {
            return false;
            //软键盘未弹出
        }
    }

}
